package com.dailyblue.java.spring.boot.jwt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.spring.boot.jwt.bean.User;
import com.dailyblue.java.spring.boot.jwt.exception.UserCodeNotFoundException;
import com.dailyblue.java.spring.boot.jwt.exception.UserPasswordErrorException;
import com.dailyblue.java.spring.boot.jwt.mapper.UserMapper;
import com.dailyblue.java.spring.boot.jwt.service.UserService;
import com.dailyblue.java.spring.boot.jwt.util.JsonResult;
import com.dailyblue.java.spring.boot.jwt.util.JwtConfig;
import com.dailyblue.java.spring.boot.jwt.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(User user) throws UserCodeNotFoundException, UserPasswordErrorException {
        log.info("输入的内容是：{}",user);
        // 连接数据库，判断账号是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userCode", user.getUserCode());
        User user1 = super.getOne(wrapper);
        if (user1 == null) {
            throw new UserCodeNotFoundException("账号不存在！");
        }
        // 判断密码是否一致
        String pass1 = user1.getPassword();  // 数据库密码
        String pass2 = user.getPassword();   // 输入的密码
        pass2 = DigestUtils.md5Hex(pass2);
        log.info("数据库密码:{},输入的密码:{}", pass1, pass2);
        if (!pass1.equals(pass2)) {
            throw new UserPasswordErrorException("密码错误！");
        }
        // 账号和密码都正确
        String jwtToken = JwtConfig.getJwtToken(user1);
        // 1. 服务器保存 token
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        value.set("token:" + user1.getId(), jwtToken);
        // 2. 发送给客户端
        return ResultTool.success(jwtToken);
    }
}
